package com.lagou.server.handler;

import com.lagou.server.service.dto.RpcRequest;
import com.lagou.server.service.dto.RpcResponse;
import com.lagou.server.util.SpringBootUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.lang.reflect.Method;
import java.util.UUID;

/**
 * 用户服务处理类
 * @author yzh
 */
public class UserServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object para) throws Exception {
        RpcRequest rpcRequest = (RpcRequest)para;
        Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(rpcRequest.getClassName());
        Object object = SpringBootUtil.getApplicationContext().getBean(clazz);
        Method method = clazz.getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
        method.setAccessible(true);
        Object result = method.invoke(object, rpcRequest.getParameters());
        RpcResponse response = new RpcResponse();
        response.setResponseID(UUID.randomUUID().toString().replaceAll("-", ""));
        response.setResult(result);
        ctx.writeAndFlush(response);
    }

}
